package com.lixh.sdk.base.util

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Resources
import android.os.Build
import android.os.Environment
import android.util.DisplayMetrics
import android.webkit.WebSettings
import androidx.core.content.FileProvider
import com.lixh.sdk.base.BaseApplication
import java.io.File


val applicationContext
    get() = BaseApplication.appContext

val application
    get() = BaseApplication.instance

val packageName: String
    get() = application.packageName

//----------屏幕尺寸----------
val displayMetrics: DisplayMetrics
    get() = Resources.getSystem().displayMetrics

val screenHeight: Float
    get() = displayMetrics.heightPixels.toFloat()

val screenWidth: Float
    get() = displayMetrics.widthPixels.toFloat()

val versionName: String
    get() = try {
        application.packageManager.getPackageInfo(packageName, 0).versionName
    } catch (e: PackageManager.NameNotFoundException) {
        ""
    }


var serialNo: String = sysSerialNo()


fun sysSerialNo(): String {
    var serial: String? = null;
    try {
        val c = Class.forName("android.os.SystemProperties")
        val get = c.getMethod("get", String::class.java)
        serial = get.invoke(c, "ro.serialno") as String
    } catch (e: Exception) {
        e.printStackTrace();
    }
    return serial ?: Build.SERIAL ?: ""
}

//修改了okhttp请求头和标准请求不一致的错误
fun getUserAgent(): String {
    val userAgent = try {
        WebSettings.getDefaultUserAgent(applicationContext)
    } catch (e: Exception) {
        System.getProperty("http.agent") as String
    } + "okhttp\u2000AndroidApp\u2000app_version=${versionName}"
    //调整编码，防止中文出错
    val sb = StringBuffer()
    var i = 0
    val length = userAgent.length
    while (i < length) {
        val c = userAgent[i]
        if (c <= '\u001f' || c >= '\u007f') {
            sb.append(String.format("\\u%04x", c.code))
        } else {
            sb.append(c)
        }
        i++
    }
    return sb.toString()
}

/**
 * 创建 DIRECTORY_DOWNLOADS 下载输出目录
 *
 * @return
 */
fun String.createDirectoryDownloadsPath(): String {
    val customFile: File
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        // 在Android Q上不能直接使用外部存储目录
        val externalFilesDir: File =
            application.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!
        customFile = File(externalFilesDir.absolutePath, this)
        // 确保目录存在，如果不存在则创建
        customFile.parentFile?.mkdirs()
        if (!customFile.exists()) {
            customFile.createNewFile()
        } else {
            customFile.deleteOnExit()
        }
    } else {
        val rootFile = Environment.getExternalStorageDirectory()
        customFile =
            File(rootFile.absolutePath + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + this)
        // 确保目录存在，如果不存在则创建
        customFile.parentFile?.mkdirs()
        if (!customFile.exists()) {
            customFile.createNewFile()
        } else {
            customFile.deleteOnExit()
        }
    }
    return customFile.absolutePath
}

/**
 * 获取未安装的apk信息
 */
fun String.getUnInstallApkInfo(): Boolean {
    var result = false
    try {
        val pm = application.packageManager
        val info = pm.getPackageArchiveInfo(this, PackageManager.GET_ACTIVITIES)
        if (info != null) {
            result = true //完整
        }
    } catch (ignored: Exception) {
    }
    return result
}

/**
 * 安装应用
 */
fun String.update(onError: (String) -> Unit) {
    runCatching {
        val apkFile = File(this)
        val fileProvider = "${packageName}.fileProvider"
        val intent = Intent(Intent.ACTION_INSTALL_PACKAGE)
        if (apkFile.exists()) {
            chmod(apkFile.absolutePath) //授权
            intent.setDataAndType(
                FileProvider.getUriForFile(applicationContext, fileProvider, apkFile),
                "application/vnd.android.package-archive"
            )
            intent.addFlags(
                Intent.FLAG_ACTIVITY_NEW_TASK or
                        Intent.FLAG_GRANT_READ_URI_PERMISSION or
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            )
            applicationContext.startActivity(intent)
        } else {
            onError.invoke("安装失败,安装文件未找到")
        }
    }.onFailure {
        it.printStackTrace()
    }
}

fun chmod(path: String) {
    val chmodCmd = "chmod 666 $path"
    try {
        Runtime.getRuntime().exec(chmodCmd)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
